#include "CWorldCollision.h"

CWorldCollision::CWorldCollision()
{

}

CWorldCollision::~CWorldCollision()
{

}

CWorldCollision* CWorldCollision::GetInstance()
{
	static CWorldCollision instance;
	return &instance;
}

void CWorldCollision::CollideWithTile(CBase* pBase, CLevelCollision* pTile)
{
	float tx = pTile->GetPosX();
	float ty = pTile->GetPosY();
	float txw = pTile->GetHalfWidth();
	float tyw = pTile->GetHalfHeight();

	float dx = pBase->GetPosX() - tx;
	float px = (txw + pBase->GetHalfWidth()) - abs(dx);

	if(0 < px)
	{
		float dy = pBase->GetPosY() - ty;
		float py = (tyw + pBase->GetHalfHeight()) - abs(dy);
		if(0 < py)
		{
			//	Object may be colliding with tile -> call collision function
			//	Calculate projection vectors
			if(px < py)
			{
				//	project in x
				if(dx < 0)
				{
					//	project to the left
					px *= -1;
					py = 0;
				}
				else
				{
					//	project to the right
					py = 0;
				}
			}
			else
			{
				//	project in y
				if(dy < 0)
				{
					//	project up
					px = 0;
					py *= -1;
				}
				else
				{
					//	project down
					px = 0;
				}
			}

			//	Call projection Function
			Proj(px, py, pBase, pTile);
		}
	}
}

void CWorldCollision::Proj(float x, float y, CBase* pBase, CLevelCollision* pTile)
{
	float length = sqrt(x*x + y*y);
	ReportCollisionVsWorld(x,y,x/length,y/length,pBase);
}

void CWorldCollision::ReportCollisionVsWorld(float px, float py, float dx, float dy, CBase* obj)
{
	obj->SetOldPosX(obj->GetPosX() + px);
	obj->SetOldPosY(obj->GetPosY() + py);
	obj->SetPosX(obj->GetPosX() + px);
	obj->SetPosY(obj->GetPosY() + py);
}